<template>
  <section class="todoapp">
    <HmHeader @add="handleAdd"></HmHeader>
    <HmMain @changAll="handleAll" @del="handleDel" @changeState="handleChangeState" :list="showList"></HmMain>
    <HmFooter  @changeType="handleType" @clear="handleClear" :list="list" :type='type'></HmFooter>
  </section>
</template>

<script>
import HmHeader from "./components/hm-header.vue"
import HmMain from "./components/hm-main.vue"
import HmFooter from "./components/hm-footer.vue"
export default {
  components:{
    HmHeader,
    HmMain,
    HmFooter,
  },
  data(){
    return{
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type:'all'
    }
  },
  computed:{
    showList(){
      if(this.type==='all') {
        return this.list
      } else if (this.type === 'active') {
        return this.list.filter(item=>item.flag===false)
      } else {
        return this.list.filter(item=>item.flag===true)
      }
    }
  },
  methods:{
    handleDel(id){
      this.list = this.list.filter(item=>item.id !== id)
    },
    handleAdd(todoName){
      this.list.unshift({
        id: +new Date(),
        name:todoName,
        flag: false,
      })
    },
    handleChangeState(flag,id){
      const obj = this.list.find(item => item.id===id)
      obj.flag = flag
    },
    handleClear(){
      this.list = this.list.filter(item=>item.flag===false)
    },
    handleType(type){
      this.type=type
    },
    changeAll(flag){
      this.list.forEach(item=>item.flag=flag)
    }
  },
  watch : {
    list:{
      deep:true,
      handler(newValue){
        localStorage.setItem('todoList', JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style></style>
